//
//  LiveUtils.swift
//  SiliUtility
//
//  Created by Li Dong on 2023/7/20.
//

import UIKit
import Photos
import AVFoundation



class LiveUtils: NSObject {
    
    static func convertVideoToMOV(inputURL: URL, outputURL: URL, completion: @escaping (Bool, Error?) -> Void) {
        let avAsset = AVURLAsset(url: inputURL, options: nil)
        
        let exportSession = AVAssetExportSession(asset: avAsset, presetName: AVAssetExportPresetHighestQuality)
        exportSession?.outputFileType = AVFileType.mov
        exportSession?.outputURL = outputURL
        exportSession?.shouldOptimizeForNetworkUse = true
        
        exportSession?.exportAsynchronously(completionHandler: {
            switch exportSession?.status {
            case .completed:
                print("Video convert: SUCCESS")
                completion(true, nil)
            case .failed:
                print("Video convert: FAILED", exportSession?.error?.localizedDescription ?? "")
                completion(false, exportSession?.error)
            case .cancelled:
                print("Video convert: CANCELLED")
                completion(false, exportSession?.error)
            default: break
            }
        })
    }

    
    
    static func exportLivePhoto(videoUrl: URL, imgUrl: URL, completion: @escaping (_ livePhoto: PHLivePhoto?) -> Void)  {
        let img = try? UIImage(data: Data(contentsOf: imgUrl))
        PHLivePhoto.request(withResourceFileURLs: [videoUrl, imgUrl], placeholderImage: img, targetSize: img!.size, contentMode: .aspectFill) { livePhoto, info in
            if livePhoto != nil  {
                print("livePhoto生成")
            }
            completion(livePhoto)
        }
         
    }
    
    static func extractResources(from livePhoto: PHLivePhoto, completion: @escaping (_ movPath: URL?, _ jpgPath: URL?) -> Void) {
        // 获取 Live Photo 的资源
        let resources = PHAssetResource.assetResources(for: livePhoto)

        // 寻找并导出 MOV 和 JPG 文件
        let movPath = URL(fileURLWithPath: CompressedHelper.shared.getFilePath(fileName: "123.mov"))
        let jpgPath = URL(fileURLWithPath: CompressedHelper.shared.getFilePath(fileName: "456.jpg"))
        for resource in resources {
            if resource.type == .pairedVideo {
                exportResource(resource, movPath)
            } else if resource.type == .photo {
                exportResource(resource, movPath)
            }
        }

        // 回调
        completion(movPath, jpgPath)
    }

    static  func exportResource(_ resource: PHAssetResource, _ fileUrl: URL) {
        // 创建一个临时文件的 URL
//        let fileURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("uuids")

        // 导出资源
        let options = PHAssetResourceRequestOptions()
        options.isNetworkAccessAllowed = true
        PHAssetResourceManager.default().writeData(for: resource, toFile: fileUrl, options: options, completionHandler: { (error) in
            if let error = error {
                print("导出资源失败: \(error)")
                return
            }
        })

    }


    static func createLivePhotoFromVideo(videoURL: URL,assetIdentifier: String, completion: ((Bool) -> Void)? ) {
        // 加载视频文件
        let asset = AVAsset(url: videoURL)
        
        // 生成静态图片
        let generator = AVAssetImageGenerator(asset: asset)
        generator.appliesPreferredTrackTransform = true // 应用视频方向
        if let cgImage = try? generator.copyCGImage(at: CMTimeMake(value: 1, timescale: 60), actualTime: nil) {
            let image = UIImage(cgImage: cgImage)
            
            // 保存静态图片
            let imageURL = saveImageToTemporaryDirectory(image: image)
            let outPath = outputImgPath()
            JPEG(path: imageURL.path).write(outPath, assetIdentifier: assetIdentifier)
            // 保存Live Photo
            saveLivePhotoToAlbum(movPath: videoURL, jpgPath: URL(fileURLWithPath: outPath), completion: completion)
          
        } else {
            print("生成静态图片失败")
        }
    }

    static func saveImageToTemporaryDirectory(image: UIImage) -> URL {
        let fileName = "temp_img.png"
        if FileManager.default.fileExists(atPath: CompressedHelper.shared.getFilePath(fileName: fileName)) {
            try? FileManager.default.removeItem(atPath: CompressedHelper.shared.getFilePath(fileName: fileName))
        }
        if let imageData = image.jpegData(compressionQuality: 1.0) {
            CompressedHelper.shared.writeData(data: imageData, fileName: fileName)
        }
        return URL(fileURLWithPath: CompressedHelper.shared.getFilePath(fileName: fileName))
    }

    static func outputImgPath() -> String {
        let fileName = "temp_img_new.jpg"
        if FileManager.default.fileExists(atPath: CompressedHelper.shared.getFilePath(fileName: fileName)) {
            try? FileManager.default.removeItem(atPath: CompressedHelper.shared.getFilePath(fileName: fileName))
        }
        return CompressedHelper.shared.getFilePath(fileName: fileName)
    }
    
   static func saveLivePhotoToAlbum(movPath: URL, jpgPath: URL, completion: ((Bool) -> Void)?) {
       PHPhotoLibrary.requestAuthorization { status in
           if status == .authorized {
               PHPhotoLibrary.shared().performChanges({
                   // 创建Live Photo的请求
                   let creationRequest = PHAssetCreationRequest.forAsset()
                   let options = PHAssetResourceCreationOptions()
                   
                   // 添加MOV和JPG文件
                   creationRequest.addResource(with: .pairedVideo, fileURL: movPath, options: options)
                   creationRequest.addResource(with: .photo, fileURL: jpgPath, options: options)
               }) { (success, error) in
                   if success {
                       print("保存Live Photo成功!")
                   } else if let error = error {
                       print("保存Live Photo失败: \(error.localizedDescription)")
                   }
                   completion?(success)
                   
               }
           }else {
               PermissionUtils.showSystemAlert(title: "无法保存到相册", message: "请在iPhone的设置中，授权app访问相册")
           }
       }
  

    }
}
